/**
 * Created by xnr on 20/2/24.
 */
// 18148124113
// 18281535489
import { router } from "../router";
import axios from "axios";
import qs from "qs";
import { Loading, MessageBox } from "element-ui";
import store from "../store";

const instance = axios.create({
  // baseURL: "http://192.168.0.78:8888/",
  baseURL: "http://124.70.164.30:9090/", // api的base_url
  // baseURL: 'http://47.102.158.69:8888/', // api的base_url
  timeout: 15000 // 请求超时时间
});
let loadingInstance = null;
let aler = 0;
// request拦截器
instance.interceptors.request.use(
  e => {
    e.params = e.params || {};
    e.headers = e.headers || {};
    e.headers["Accept"] = "application/json";

    //导出参数
    if (e.requestBody == "download") {
      (e.responseType = "arraybuffer"), //二进制流
        (e.data = qs.stringify(e.data, { arrayFormat: "repeat" }));
    }

    // POST传参序列化
    else if (e.requestBody == "body") {
      e.headers["Content-Type"] = "application/json";
      e.data = JSON.stringify(e.data);
    } else {
      e.data = qs.stringify(e.data, { arrayFormat: "repeat" });
    }
    // var token = store.getters.get_token;
    var token = {
      token:
        "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiLmnajlkozpkasiLCJsaWNlbnNlIjoicHJvZHVjZSBieSB3ZWlsYWk5LmNvbSIsIml0ZW1JZCI6bnVsbCwiaXRlbVR5cGUiOjQsImN1c3RvbWVySWQiOjgsImlzcyI6IldMSiIsImF1dGhvcml0aWVzIjpudWxsLCJzdGF0dXMiOjF9.cMK8sFOVqT9jBcdM-owVtB8XoC8FHYOgKQolj7kvEEWfK98FxO_EzhJhykC5C4WGzIS4FJ2IwNNPtlvKIu1F3w"
    };
    if (token) {
      e.headers["Authorization"] = "WLJ" + " " + token.token;
    }
    // 自定义加载图标
    if (e.loading && !loadingInstance) {
      loadingInstance = Loading.service({
        text: "拼命请求中",
        background: "rgba(0,0,0,0.3)",
        customClass: "LoadingClass"
      });
    }
    //set 默认值
    return e;
  },
  error => ({ status: 0, msg: error.message })
);
// respone拦截器
instance.interceptors.response.use(
  response => {
    const resp = response.data;
    if (loadingInstance) {
      setTimeout(function() {
        loadingInstance && loadingInstance.close();
        loadingInstance = null;
      }, 300);
    }
    if (response.status === 200) {
      if (resp.code == 110 && aler == 0) {
        aler = 1;
        MessageBox.alert("您登录已过期，请重新登录").then(() => {
          aler = 0;
          window.sessionStorage["vuex"] = "";
          router.push("/Login");
        });
      } else {
        return resp;
      }
    }
  },
  error => {
    if (loadingInstance) {
      setTimeout(function() {
        loadingInstance && loadingInstance.close();
        loadingInstance = null;
      }, 300);
    }
    MessageBox.alert("您登录已过期，请重新登录").then(() => {
      router.push({ name: "login" });
    });
    // eslint-disable-next-line no-console
    console.log("err" + error); // for debug
    return Promise.reject(error);
  }
);
export default instance;
